﻿@page "/testble"

@using MaBlaApp.Data
@inject BleTester MyBleTester

<h3>测试低功耗蓝牙</h3>

<ul class="list-group">
    <li class="list-group-item">
        <button type="button" class="btn btn-primary btn-sm" @attributes=IsScanningCss @onclick=ScanDevice>扫描外设</button>
    </li>
    @if (IsFound)
    {
        <li class="list-group-item">
            <strong>@MyBleTester.TagDeviceInfo</strong>
        </li>
        <li class="list-group-item">
            <button type="button" class="btn btn-primary btn-sm" @onclick=ConnectDevice>连接外设</button>
        </li>
        @if (IsConnected)
        {
            <li class="list-group-item">
                <button type="button" class="btn btn-primary btn-sm" @onclick=ReadDeviceName>读取设备名</button>
            </li>
            <li class="list-group-item">
                <strong>@MyBleTester.ReadDeviceNameResult</strong>
            </li>
        }
    }
</ul>

@code {

    private bool IsScanning = false;
    private bool IsFound = false;
    private bool IsConnected = false;
    private bool IsReadSuccess = false;

    private Dictionary<string, object>? IsScanningCss => IsScanning ? new() { { "disabled", "" }, } : null;

    //扫描外设
    private async void ScanDevice()
    {
        MyBleTester.TagDeviceName = "honor Band 4-7E8";

        IsScanning = true;
        IsFound = false;

        //开始扫描
        IsFound = await MyBleTester.StartScanAsync();

        IsScanning = false;

        //异步更新UI
        await InvokeAsync(() => StateHasChanged());
    }

    //连接外设
    private async void ConnectDevice()
    {
        //连接外设
        IsConnected = await MyBleTester.ConnectDeviceAsync();

        //异步更新UI
        await InvokeAsync(() => StateHasChanged());
    }

    //读取设备名
    private async void ReadDeviceName()
    {
        //读取设备名
        IsReadSuccess = await MyBleTester.ReadDeviceName();

        //异步更新UI
        await InvokeAsync(() => StateHasChanged());
    }
}
